<?php
class Admin_NewsController extends Zendhlt_Controller_AdminAction {

	const ADD_PAGE_TITLE = 'Thêm bài viết';
	const LIST_PAGE_TITLE = 'Danh sách bài viết';
	const EDIT_PAGE_TITLE = 'Chỉnh sửa bài viết';
	const NEWS_IMAGE_WIDTH1 = 94;
	const NEWS_IMAGE_HEIGHT1 = 94;
	const NEWS_IMAGE_WIDTH2 = 50;
	const NEWS_IMAGE_HEIGHT2 = 50;
	const ACTIVE = 1;

	private $_currentUser;
	private $_arrParam;
	private $_paginator = array();
	private $_actionMain;
	private $_namespace;

	public function init() {
		$layoutPath = TEMPLATE_PATH . '/admin';
		$option = array('layout'     => 'index',
                   		'layoutPath' => $layoutPath);
		Zend_Layout::startMvc($option);

		// Phân trang
		$this->_paginator['itemCountPerPage'] = 5;
		$this->_paginator['pageRange'] 		  = 3;
		$this->_paginator['currentPage'] 	  = $this->_request->getParam('page', 1);

		// Mang tham so nhan duoc o moi Action
		$this->_arrParam = $this->_request->getParams();

		// Duong dan cua Action chinh
		$this->_actionMain = '/' . $this->_arrParam['module'] . '/' . $this->_arrParam['controller'];

		// Dat ten SESSION
		// Luu cac du lieu filter vao SESSION
		$this->_namespace = $this->_arrParam['module'] . '-' . $this->_arrParam['controller'];
		$ssFilter = new Zend_Session_Namespace($this->_namespace);

		if(empty($ssFilter->col) || ($this->_request->getParam('resetfilter', 0) == 1)) {
			$ssFilter->keywords 	= '';
			$ssFilter->col 			= 'ngay_tao';
			$ssFilter->order 		= 'DESC';
			$ssFilter->state 		= self::ACTIVE;
			$ssFilter->error 		= 0;
		}

		$this->_arrParam['paginator']			 = $this->_paginator;
		$this->_arrParam['ssFilter']['keywords'] = $ssFilter->keywords;
		$this->_arrParam['ssFilter']['col'] 	 = $ssFilter->col;
		$this->_arrParam['ssFilter']['order'] 	 = $ssFilter->order;
		$this->_arrParam['ssFilter']['state'] 	 = $ssFilter->state;

		// Truyen ra view
		$this->view->actionMain = $this->_actionMain;
		$this->view->currentController = '/' . $this->_arrParam['module'] . '/' . $this->_arrParam['controller'];
		$this->view->arrParam = $this->_arrParam;

		// Lay thong tin user admin hien tai
		$auth = Zend_Auth::getInstance();
		$this->_currentUser = $auth->getIdentity();
	}

	public function indexAction() {
		$this->view->headTitle(self::LIST_PAGE_TITLE);

		$model = new Admin_Model_NewsMapper();
		$paginator = new Zendhlt_Paginator();

		$newses = $model->fetch($this->_arrParam);
		$totalItem = $model->countItem($this->_arrParam);

		$this->view->panigator = $paginator->createPaginator($totalItem, $this->_paginator);
		$this->view->totalItems = $totalItem;
		$this->view->Items = $newses;

		// Display error if delete occur error {
		$ssFilter = new Zend_Session_Namespace($this->_namespace);
		$this->view->msg = '';

		if ($ssFilter->error == 1) {
			$this->view->msg = 'Xuất hiện lổi trong quá trình thực hiện!';
			$ssFilter->error = 0;
		}
		// }
	}

	public function addAction() {
		$this->view->headTitle(self::ADD_PAGE_TITLE);

		$form = new Admin_Form_News();
		$form->hinh_anh->setRequired(true);
		$form->luot_xem->setValue(0);
		$this->view->form = $form;
		$this->view->msg = '';

		$model = new Admin_Model_NewsMapper();

		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();

			if ($form->isValid($formData)) {
				$upload = new Zendhlt_File_Upload();
				$newFileName = $upload->upload('hinh_anh', TMP_PATH, array('task' => 'rename'));

				$img1 = Zendhlt_File_Image::create(TMP_PATH . $newFileName);
				$img1->resizeCustom(self::NEWS_IMAGE_WIDTH1, self::NEWS_IMAGE_HEIGHT1);
				$img1->save(NEWS_IMAGES_PATH . NEWS_IMAGE_PREFIX1 . '/' . NEWS_IMAGE_PREFIX1 . $newFileName);

				$img2 = Zendhlt_File_Image::create(TMP_PATH . $newFileName);
				$img2->resizeCustom(self::NEWS_IMAGE_WIDTH2, self::NEWS_IMAGE_HEIGHT2);
				$img2->save(NEWS_IMAGES_PATH . NEWS_IMAGE_PREFIX2 . '/' . NEWS_IMAGE_PREFIX2 . $newFileName);

				unlink(TMP_PATH . $newFileName);

				$news = new Admin_Model_TableColumn_News($formData);
				$news->setId(0);
				$news->setHinh_anh($newFileName);
				$news->setNguoi_tao($this->_currentUser->id);
				$news->setNguoi_cap_nhat($this->_currentUser->id);
				$news->setTrang_thai(self::ACTIVE);

				if ($model->save($news)) {
					$form->reset();
					$form->luot_xem->setValue(0);
				} else {
					$this->view->msg = 'Xuất hiện lỗi trong quá trình thực hiện';
					$form->populate($formData);
				}
			} else {
				$form->populate($formData);
			}
		}
	}

	public function filterAction() {
		$ssFilter = new Zend_Session_Namespace($this->_namespace);

		if ($this->_arrParam['type'] == 'search') {
			if($this->_arrParam['key'] == 1) {
				$ssFilter->keywords = trim($this->_arrParam['keywords']);
				$ssFilter->state = $this->_arrParam['state'];
			} else {
				$ssFilter->keywords = '';
				$ssFilter->state = self::ACTIVE;
			}
		}

		if ($this->_arrParam['type'] == 'order') {
			$ssFilter->col = $this->_arrParam['col'];
			$ssFilter->order = $this->_arrParam['by'];
		}

		$this->_redirect($this->_actionMain . '/index');
		$this->_helper->viewRenderer->setNoRender();
	}

	public function editAction() {
		$this->view->headTitle(self::EDIT_PAGE_TITLE);

		$form = new Admin_Form_News();
		$form->hinh_anh->setRequired(false);
		$this->view->form = $form;
		$this->view->msg = '';

		$model = new Admin_Model_NewsMapper();
		$arrData = $model->fetchAll('id=' . $this->_getParam('id', 0), 'edit');
		$data = array_shift($arrData);

		if ($data != null) {
			if ($this->getRequest()->isPost()) {
				$formData = $this->getRequest()->getPost();

				if ($form->isValid($formData)) {
					$news = new Admin_Model_TableColumn_News($data);

					if (is_uploaded_file($_FILES['hinh_anh']['tmp_name'])) {
						unlink(NEWS_IMAGES_PATH . NEWS_IMAGE_PREFIX1 . '/' . NEWS_IMAGE_PREFIX1 . $news->getHinh_anh());
						unlink(NEWS_IMAGES_PATH . NEWS_IMAGE_PREFIX2 . '/' . NEWS_IMAGE_PREFIX2 . $news->getHinh_anh());

						$upload = new Zendhlt_File_Upload();
						$newFileName = $upload->upload('hinh_anh', TMP_PATH, array('task' => 'rename'));

						$img1 = Zendhlt_File_Image::create(TMP_PATH . $newFileName);
						$img1->resizeCustom(self::NEWS_IMAGE_WIDTH1, self::NEWS_IMAGE_HEIGHT1);
						$img1->save(NEWS_IMAGES_PATH . NEWS_IMAGE_PREFIX1 . '/' . NEWS_IMAGE_PREFIX1 . $newFileName);

						$img2 = Zendhlt_File_Image::create(TMP_PATH . $newFileName);
						$img2->resizeCustom(self::NEWS_IMAGE_WIDTH2, self::NEWS_IMAGE_HEIGHT2);
						$img2->save(NEWS_IMAGES_PATH . NEWS_IMAGE_PREFIX2 . '/' . NEWS_IMAGE_PREFIX2 . $newFileName);

						unlink(TMP_PATH . $newFileName);

						$news->setHinh_anh($newFileName);
					}

					$news->setTieu_de($form->getValue('tieu_de'));
					$news->setGioi_thieu($form->getValue('gioi_thieu'));
					$news->setNoi_dung($form->getValue('noi_dung'));
					$news->setLuot_xem($form->getValue('luot_xem'));
					$news->setNguoi_cap_nhat($this->_currentUser->id);

					if ($model->save($news)) {
						$this->_redirect($this->_actionMain . '/index/page/' . $this->_paginator['currentPage']);
					} else {
						$this->view->msg = 'Xuất hiện lổi trong quá trình thực hiện.';
						$form->populate($formData);
					}
				} else {
					$form->populate($formData);
				}
			} else {
				$form->populate($data);
			}
		} else {
			$this->view->msg = 'Dữ liệu không tồn tại trong database.';
		}
	}

	// Update trang thai ẩn|hiện
	public function deleteAction() {
		$model = new Admin_Model_NewsMapper();

		if (isset($this->_arrParam['id'])) {
			$id = $this->_arrParam['id'];
		} elseif (isset($this->_arrParam['cid'])) {
			$id = $this->_arrParam['cid'];
		}

		if ($id != null) {
			$state = $this->_arrParam['delete-type'];

			if ($model->deleteItems($id, $state, $this->_currentUser->id) == false) {
				$ssFilter = new Zend_Session_Namespace($this->_namespace);
				$ssFilter->error = 1;
			}
		}

		$this->_redirect($this->_actionMain . '/index');
		$this->_helper->viewRenderer->setNoRender();
	}

	// Xoá du lieu trong database
	public function removeAction() {
		$model = new Admin_Model_NewsMapper();
		$ssFilter = new Zend_Session_Namespace($this->_namespace);

		if (isset($this->_arrParam['cid'])) {
			$ids = $this->_arrParam['cid'];

			foreach ($ids as $id) {
				$arrData = $model->fetchAll("id = $id", 'edit');
				$data = array_shift($arrData);
					
				if ($data != null) {
					$news = new Admin_Model_TableColumn_News($data);
				
					if ($model->removeItems($id) == false) {
						$ssFilter->error = 1;
				
					} else {
						unlink(NEWS_IMAGES_PATH . NEWS_IMAGE_PREFIX1 . '/' . NEWS_IMAGE_PREFIX1 . $news->getHinh_anh());
						unlink(NEWS_IMAGES_PATH . NEWS_IMAGE_PREFIX2 . '/' . NEWS_IMAGE_PREFIX2 . $news->getHinh_anh());
					}
				
				} else {
					$ssFilter->error = 1;
				}
			}
		}

		$this->_redirect($this->_actionMain . '/index');
		$this->_helper->viewRenderer->setNoRender();
	}

}
?>